import { Component, OnInit } from '@angular/core';
import { UrlService } from 'src/app/service/url.service';
import { HttpService } from 'src/app/service/http.service';
import { ToolService } from 'src/app/service/tool.service';
import { ConfigService } from 'src/app/service/config.service';
import { PopwinService } from 'src/app/service/popwin.service';
import { NavController } from '@ionic/angular';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'app-wallet',
  templateUrl: './wallet.page.html',
  styleUrls: ['./wallet.page.scss'],
})
export class WalletPage implements OnInit {

  public totalBalance="0.00";//总资产
  public totalWin="0.00";
  public balanceList=[];//
  constructor(private http:HttpService,private popWin:PopwinService,private navCtrl:NavController,private store:Storage) { }

  ngOnInit() {
    if(!ConfigService.is3rd){//没有第三方直接放回
      this.backClick();
      return;
    }
    let that=this;
    this.store.get(ConfigService.ROLE_KEY).then((data) => {
      if (data == '2') {
        that.popWin.toast("试玩账号不能进入");
        that.backClick();
        return;
      }
      that.getBalanceData();
    });


    
  }

  getBalanceData(isFirst=true){
    let that=this;
    this.http.get(UrlService.OTHER_BALANCE, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let res = ToolService.aesDecodeToJson(data.data);
        let error=res.error;
        res=res.data;
        if(!ToolService.isEmpty(res) && res.length>=1){
            that.balanceList=res;
            that.totalBalance=that.calcTotalBalance(res,'balance');
            that.totalWin=that.calcTotalBalance(res,'win');
            if(!ToolService.isEmpty(error)){
              that.popWin.toast(error);
            }
        }
        if(!isFirst){
          that.popWin.toast("刷新成功");
        }
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }

  backClick(){
    this.navCtrl.back();
  }

  onRefresh(){
    this.getBalanceData(false);
  }
  /**
   * 返回统计的总的余额
   * @param balanceList 所有的余额的值
   * @param key  具体是balance还是win
   */
  calcTotalBalance(balanceList,key){
    let res="0.00";
    for(let item in balanceList){
      res=(parseFloat(res)+parseFloat(balanceList[item][key])).toFixed(2);
    }
    return res;
  }
  /**
   * 跳转到充值纪录页面
   */
  toTransactionPage(){
      this.navCtrl.navigateForward("/transaction");
  }

}
